import sm2Encrypt from 'sm2js'
import { defineStore } from "pinia";
import { ElMessage } from 'element-plus'
import { useLocalStorage } from '@/hooks'
import { login, getUserInfo } from '@/api'
import type { rulesLoginFormVO } from '@/interface'
import { getToken, removeToken, setToken } from '@/utils/auth'
/**
 * 用户Model的静态数据
 */
const getDefaultState = () => {
  return {
    userId: getToken(),
    name: '',
    avatar: '',
    userInfo: ''
  }
}

/**
 * 用户相关仓库
 */
export const userStores = defineStore({
  id: "user",
  state: () => ({
    ...getDefaultState(),
  }),
  actions: {
    // 登录reducer
    login(payload: rulesLoginFormVO) {
      const { username, password, code } = payload
      const cipherMode = 0
      const username1 = sm2Encrypt(username.trim(), import.meta.env.VITE_LOGIN_KEY, cipherMode)
      const password1 = sm2Encrypt(password, import.meta.env.VITE_LOGIN_KEY, cipherMode)
      const code1 = sm2Encrypt(code.trim(), import.meta.env.VITE_LOGIN_KEY, cipherMode)
      return new Promise(async (resolve, reject) => {
        const { status, data } = await login({ userId: username1, password: password1, code: code1 })
        if (status === 0 && data) {
          this.userInfo = data
          this.userId = data.userId
          setToken(data.userId)
          useLocalStorage.setItem('userInfo', JSON.stringify(data))
          useLocalStorage.setItem('token', data.userId)
          ElMessage.success('登录成功')
          resolve(data)
        } else {
          reject({})
        }
      })
    },
    // 获取用户信息
    getUserInfo() {
      return new Promise((resolve, reject) => {
        getUserInfo({ userId: getToken() })
          .then((response) => {
            const { status, data } = response
            if (!data && status !== 0) {
              reject('验证失败，请重新登录！')
            } else {
              useLocalStorage.setItem('userInfo', JSON.stringify(data))
            }
            const { userId } = data
            this.name = userId
            resolve(data)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 删除用户信息
    resetToken() {
      return new Promise((resolve) => {
        removeToken()
        useLocalStorage.clear()
        Object.assign(this, getDefaultState())
        resolve()
      })
    }
  },
});
